﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GenericRepository;
using Entities;


namespace NorthwindMvc.Controllers
{
    public class ProductController : Controller
    {
        //
        // GET: /Product/

        public ActionResult Index()
        {
            var rep = new Repository(ContextFactory.GetContext());
            var listProduct = rep.GetAll<Products>().ToList();
            return View(listProduct);
        }

        public ActionResult Create()
        {
            var rep = new Repository(ContextFactory.GetContext());
            ViewBag.Suppliers = new SelectList(rep.GetAll<Suppliers>(), "SupplierID", "CompanyName");
            ViewBag.Categories = new SelectList(rep.GetAll<Categories>(), "CategoryID", "CategoryName");
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Products model)
        {
            var rep = new Repository(ContextFactory.GetContext());
            rep.Add(model);
            rep.UnitOfWork.SaveChanges();
            return RedirectToAction("Index");
        }

        public  ActionResult Edit(int id)
        {
            var rep = new Repository(ContextFactory.GetContext());
            var model = rep.GetByKey<Products>(id);
            ViewBag.Suppliers = new SelectList(rep.GetAll<Suppliers>(), "SupplierID", "CompanyName",model.SupplierID);
            ViewBag.Categories = new SelectList(rep.GetAll<Categories>(), "CategoryID", "CategoryName",model.CategoryID);
            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(Products model)
        {
            var rep = new Repository(ContextFactory.GetContext());
            rep.Update(model);
            rep.UnitOfWork.SaveChanges();
            return RedirectToAction("Index");
        }
    }
}
